<template>
  <div>
    <van-notice-bar
      left-icon="volume-o"
      text="请注意，该功能是一个实验性功能，可能会出现一些问题，请知悉。也许会在未来版本中移除。不支持连续对话，不会记忆上文。"
    />
    <t-chat
      ref="chat"
      @keysend="handleSubmit"
      :config="config"
      width="800"
      height="860"
      :placeholder="placeholder"
      @submit="handleSubmit"
      v-model="msg"
      :list="list"
      :show-key-list="false"
      @use-form="handleInsertForm"
    >
      <template #menu></template>
    </t-chat>
  </div>
</template>
<script>
import TChat from "@/views/ai/chat/index.vue";
import RebootSvg from "@/views/ai/chat/icon/reboot.svg";
import MyAvatarSvg from "@/views/ai/chat/icon/my.svg";
import { aiChatRequest } from "@/api/project/ai";
import { ElLoading } from "element-plus";
import { parseJsonToFields } from "@/views/ai/chat/convertToFields";
import { formItemConvertData } from "@/views/formgen/utils/convert";
import { batchSaveProjectItem } from "@/views/formgen/api";
import { MessageUtil } from "@/utils/messageUtil";
import mittBus from "@/utils/mitt";

export default {
  components: {
    TChat
  },
  emits: ["submit"],
  data() {
    return {
      config: {
        img: RebootSvg,
        name: "TDUCK-AI",
        myImg: MyAvatarSvg,
        myName: "我",
        dept: ""
      },
      msg: "",
      placeholder: "请输入...",
      list: [
        {
          date: "",
          text: {
            text: "发送文字，将自动生成问卷,比如：食堂满意度调查，旅游城市意向调查。"
          },
          mine: false,
          img: RebootSvg,
          name: "TDUCK-AI"
        }
      ]
    };
  },
  mounted() {},
  methods: {
    async handleSubmit(msg) {
      this.msg = msg || this.msg;
      this.$refs.chat.pushMsg({
        mine: true,
        text: this.msg
      });
      const loadingInstance = ElLoading.service({
        text: "正在努力思考中..."
      });

      try {
        const res = await aiChatRequest(this.msg);
        const fields = parseJsonToFields(res.data);
        this.$refs.chat.rootSendMsg(res.data, "form", { fields: fields });
      } catch (e) {
        console.error(e);
        this.$refs.chat.rootSendMsg("很抱歉，生成失败了");
      }
      loadingInstance.close();
      this.msg = "";
    },
    handleInsertForm(fields) {
      let itemList = fields.map(item => formItemConvertData(item, this.$route.query.key));
      batchSaveProjectItem({
        formKey: this.$route.query.key,
        list: itemList,
        operation: "add"
      }).then(() => {
        MessageUtil.success("保存成功");
        mittBus.emit("refreshFormList");
        this.$emit("submit");
      });
    }
  }
};
</script>
